// src/models/specValue.model.js

import { DataTypes } from "sequelize";

export default function initSpecValue(sequelize) {
  const SpecValue = sequelize.define(
    "SpecValue",
    {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },
      spec_type_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
          model: "SpecType",
          key: "id",
        },
      },
      value: {
        type: DataTypes.STRING,
        allowNull: false,
      },
      created_at: {
        type: DataTypes.DATE,
        defaultValue: DataTypes.NOW,
      },
      updated_at: {
        type: DataTypes.DATE,
        defaultValue: DataTypes.NOW,
      },
    },
    {
      tableName: "spec_value",
      timestamps: false,
      underscored: true,
      paranoid: false,
    }
  );

  SpecValue.associate = function (models) {
    // 关联到规格类型
    SpecValue.belongsTo(models.SpecType, {
      foreignKey: "spec_type_id",
      as: "specType",
    });
    // 在规格值模型(SkuSpecValue)中
    SpecValue.belongsTo(models.Product, {
      foreignKey: "product_id", // 使用数据库中实际的列名
      as: "products",
    });
    // 关联到SKU规格值表
    SpecValue.hasMany(models.SkuSpec, {
      foreignKey: "spec_value_id",
      as: "skuSpecs",
    });
    // 添加与SKU的多对多关联
    SpecValue.belongsToMany(models.Sku, {
      through: "sku_spec_value", // 必须与Sku模型中的中间表名相同
      foreignKey: "spec_value_id",
      as: "productSkus",
    });
  };

  return SpecValue;
}
